package com.sun.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.sun.common.Result;
import com.sun.entity.EnhanceUserExcel;
import com.sun.excel.MyDefinitionExcelStyle;
import com.sun.handler.MyDefinitionVerifyHandler;
import com.sun.service.UserExcelService;
import com.sun.utils.ValidatorUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class UserExcelController {

    @Autowired
    private UserExcelService userExcelService;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private MyDefinitionVerifyHandler myDefinitionVerifyHandler;


    /**
     * 数据导出
     * @param response
     */
    @GetMapping("/export")
    public void exportUserExcel(HttpServletResponse response) {
        List<EnhanceUserExcel> list = userExcelService.list();
        response.setContentType("application/vnd.ms-excel");
        OutputStream outputStream = null;
        try {
            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode("用户导出" + sdf.format(new Date()) + ".xls", "utf-8"));
            ExportParams exportParams = new ExportParams();
            //设置样式
            exportParams.setTitle(null);
            exportParams.setSheetName("用户信息");
            exportParams.setStyle(MyDefinitionExcelStyle.class);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, EnhanceUserExcel.class, list);
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 数据导入不带校验规则
     */
    @PostMapping("/import")
    public Result importExcelDataNoValidate(MultipartFile file) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        ExcelImportResult<EnhanceUserExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), EnhanceUserExcel.class, importParams);
        List<EnhanceUserExcel> userExcelList = result.getList();
        userExcelList.stream().forEach(x->x.setId(null));
        return Result.ok(userExcelService.saveBatch(userExcelList));
    }


    /**
     * 数据导入带检验规则
     * 校验包含两类，一类是字段值的校验 JSR303检验
     * 另外就是自定义校验规则
     */
    @PostMapping("/importValidate")
    public Result importExcelDataValidate(MultipartFile file,HttpServletResponse response) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        //JSR303校验规则
        importParams.setNeedVerify(true);
        //自定义校验规则
        //importParams.setVerifyHandler(myDefinitionVerifyHandler);
        ExcelImportResult<EnhanceUserExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), EnhanceUserExcel.class, importParams);

        if(result.isVerifyFail()){
            String validateMessage = validateMessage(result.getFailList());
            //数据校验异常，告诉用户那些数据异常，给个友好的提示信息
            return Result.fail(validateMessage);
        }

        List<EnhanceUserExcel> userExcelList = result.getList();
        userExcelList.stream().forEach(x->x.setId(null));
        return Result.ok(userExcelService.saveBatch(userExcelList));
    }


    /**
     * 对异常数据进行友好的提示
     * @param list
     * @return
     */
    public String validateMessage(List<EnhanceUserExcel> list){
        StringBuilder stringBuilder = new StringBuilder();
        if(CollectionUtils.isNotEmpty(list)){
            for (int i= 0; i< list.size();i ++) {
                int location = i + 1;
                if(!ValidatorUtil.isEmail(list.get(i).getUserEmail()) && ValidatorUtil.isNotEmpty(list.get(i).getUserName())){
                    stringBuilder.append("用户名为：【" + list.get(i).getUserName() + "】:邮箱格式不正确！");
                    stringBuilder.append("\r\n");
                }
                if(!ValidatorUtil.isNotEmpty(list.get(i).getUserName())){
                    stringBuilder.append("行号【" + location + "】:用户名称不能为空！");
                    stringBuilder.append("\r\n");
                }
            }
        }
        return stringBuilder.toString();
    }
}
